import {
  baseURL
} from "../../utils/request"
import {
  detailCamp,
  seekList,
  modifyCamp
} from '../../api/camp'
const http = require("../../api/index")
Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseURL,
    userType: "", //1运营者，2游客
    steps: [{
        desc: '营地信息',
      },
      {
        desc: '服务设施',
      },
    ],
    active: 0, //步骤条
    name: "", //名称
    open: false, //选择器状态
    latitude: "", //维度
    longitude: "", //经度
    campLocation: "", //位置
    address: "", //详细地址信息
    timeOpen: false, //控制时间选择的开关
    timeDetailOpen: false, //控制月份选择器
    timeType: 1, //营业时间类型 1全年，2月份
    time: "", //营业时间
    columns: [{
        values: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], //月份
        className: 'column1',
        defaultIndex: 0,
      },
      {
        values: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], //月份
        className: 'column2',
        defaultIndex: 2,
      },
    ],
    campTypes: ["综合营地", "微型营地", "帐篷营地", "教育营地", "运动营地"],
    checkedType: "",
    type: "", //营地类型
    contacts: "", //联系人姓名
    phone: "", //联系电话
    introduce: "", //营地介绍  
    campImgs: [], //商家信息图片(运营者)
    tourisCampImgs: [], //游客图片(非运营者)
    facilitiesList: [], //服务设施列表
    selectFacilitiesList: [], //选中的服务设施列表
    campId: "", //商家上传后的营地id
  },
  // 营地名称
  changeName(e) {
    this.setData({
      name: e.detail.value
    })
  },
  // 营地位置
  selectSite() {
    // 检查用户权限状态
    wx.getSetting({
      success: res => {
        if (!res.authSetting['scope.userLocation']) {
          // 用户尚未授权或已拒绝授权
          // 主动请求授权
          this.requestLocationAuthorization();
        } else {
          // 已经授权，直接获取位置信息
          this.getUserLocation();
        }
      }
    })
  },
  // 请求授权
  requestLocationAuthorization() {
    // 请求用户授权精确位置
    wx.authorize({
      scope: 'scope.userLocation',
      success: () => {
        this.getUserLocation();
      },
      fail: (err) => {
        // 拒绝授权，提示用户收到开启
        this.showSettingPrompt()
      }
    })
  },
  // 提示用户开启授权
  showSettingPrompt() {
    wx.showModal({
      title: '需要位置权限',
      content: '请在设置中开启位置权限以正常使用本功能。',
      showCancel: false,
      confirmText: '去设置',
      success: (res) => {
        if (res.confirm) {
          wx.openSetting({
            success: (settingRes) => {
              if (settingRes.authSetting['scope.userLocation']) {
                // 用户在设置中开启了位置权限
                this.getUserLocation();
              } else {
                // 用户仍然拒绝位置权限
                console.log('用户仍未开启位置权限');
              }
            },
          });
        }
      },
    });
  },
  //获取位置信息
  getUserLocation() {
    wx.getLocation({
      // type: 'wgs84',
      type: 'gcj02',
      success: (res) => {
        console.log(res, "返回的数据")
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        });
        wx.chooseLocation({
          longitude: this.data.longitude,
          latitude: this.data.latitude,
          success: (res) => {
            console.log(res, '########');
            this.setData({
              latitude: res.latitude,
              longitude: res.longitude,
              campLocation: res.address
            });
          },
          fail: err => {
            console.log(err)
          }
        })
      },
      fail: (err) => {
        console.error('获取位置失败:', err);
      },
      complete: () => {
        console.log('位置获取操作已完成');
      }
    });
  },
  // 具体位置
  changeAddress(e) {
    this.setData({
      address: e.detail.value
    })
  },
  //营业时间
  selectTime() {
    this.setData({
      open: false,
      timeOpen: true,
      time: "全年"
    })
  },
  onChange(e) {
    this.setData({
      timeType: e.detail
    })
    if (e.detail == 1) {
      this.setData({
        timeDetailOpen: false,
        time: "全年"
      })
    } else {
      this.setData({
        timeDetailOpen: true
      })
    }
  },
  onTimeChange(e) {
    console.log(e)
    this.setData({
      time: e.detail.value.join("-")
    })
  },
  // 关闭时间
  closeTime() {
    this.setData({
      timeOpen: false
    })
  },
  // 确定时间
  sureTime() {
    this.setData({
      timeOpen: false
    })
    console.log(this.data.time)
  },
  // 选择营地类型
  selectType() {
    this.setData({
      timeOpen: false,
      open: true
    })
  },
  bindChange(e) {
    let val = e.detail.value[0]
    this.setData({
      checkedType: this.data.campTypes[val]
    })
  },
  closeSelect() {
    this.setData({
      open: false
    })
  },
  sureSelect() {
    this.setData({
      type: this.data.checkedType || "综合营地",
      open: false
    })
  },
  // 绑定联系人
  changeContacts(e) {
    this.setData({
      contacts: e.detail.value
    })
  },
  // 绑定联系电话
  changePhone(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  // 绑定营地介绍
  changeIntroduce(e) {
    this.setData({
      introduce: e.detail.value
    })
  },
  //获取图片
  getUploadList(l) {
    console.log(l)
    this.setData({
      campImgs: l.detail,
      tourisCampImgs: l.detail
    })
  },
  //删除图片
  delImgs(u) {
    this.data.campImgs.splice(u.currentTarget.dataset.index, 1)
    this.setData({
      campImgs: this.data.campImgs
    })
  },
  // 给子组件传递数据
  transferData() {

  },
  // 下一步
  next() {
    let flag = this.checkCamp()
    if (flag) {
      this.setData({
        active: 1
      })
    }
  },
  // 禁止滑动
  catchTouchMove() {
    return false
  },
  // 获取服务设施
  async getFacilitiesList() {
    const res = await http.serviceFacilities()
    this.setData({
      facilitiesList: res.data
    })
    console.log(res)
  },
  // 选中服务设施
  selectIcon(e) {
    let a, b, select, list, id, data
    list = this.data.facilitiesList
    id = e.currentTarget.dataset.id
    data = this.data.selectFacilitiesList
    for (let i = 0; i < list.length; i++) {
      for (let j = 0; j < list[i].facilities.length; j++) {
        if (id == list[i].facilities[j].facilityId) {
          a = i
          b = j
        }
      }
    }
    select = list[a].facilities[b].state
    // 如果没有选中，则选中
    if (select == 1) {
      list[a].facilities[b].state = 2
      data.push(id)
      this.setData({
        facilitiesList: list,
        selectFacilitiesList: data
      })
    } else {
      // 已经选中，则取消选中
      list[a].facilities[b].state = 1
      let index = data.indexOf(id)
      data.splice(index, 1)
      this.setData({
        facilitiesList: list,
        selectFacilitiesList: data
      })
    }

    console.log(this.data.selectFacilitiesList);
  },
  // 上一步
  prev() {
    this.setData({
      active: 0
    })
  },
  // 游客提交数据
  async touristSub() {
    let flag = this.checkCamp()
    if (flag) {
      await this.subCamp()
      wx.showToast({
        title: '发布成功',
        icon: "success",
        mask: true,
        duration: 1500,
        success: res => {
          wx.redirectTo({
            url: `../detail/detail?campId=${this.data.campId}`,
          })
        }
      })
    }
  },
  // 商家提交数据
  async businessSub() {
    await this.subCamp()
    await this.subService()
  },
  // 校验营地信息
  checkCamp() {
    if (!this.data.name) {
      this.showToast("请输入营地名称")
      return false
    } else if (!this.data.campLocation) {
      this.showToast("请选择营地位置")
      return false
    } else if (!this.data.address) {
      this.showToast("请完善地址信息")
      return false
    } else if (!this.data.time) {
      this.showToast("请选择营业时间")
      return false
    } else if (!this.data.type) {
      this.showToast("请选择营地类型")
      return false
    } else if (!this.data.contacts) {
      this.showToast("请填写您的姓名")
      return false
    } else if (!this.data.phone) {
      this.showToast("请填写联系电话")
      return false
    } else if (!this.data.introduce) {
      this.showToast("请填写营地介绍")
      return false
    } else if (!this.data.campImgs.length) {
      this.showToast("请上传营地图片")
      return false
    } else {
      return true
    }
  },
  // 修改营地信息
  async subCamp() {
    let userInfo = wx.getStorageSync("userInfo")
    let campType = this.campType(this.data.type)
    let res = await modifyCamp({
      userId: userInfo.userId,
      userType: this.data.userType,
      campType,
      campName: this.data.name,
      longitude: this.data.longitude, //经度
      latitude: this.data.latitude,
      location: this.data.campLocation,
      address: this.data.address,
      timeType: this.data.timeType,
      specificTime: this.data.time,
      linkman: this.data.contacts,
      phone: this.data.phone,
      imageUrl: this.data.campImgs.join(","),
      introduce: this.data.introduce,
      campUser: {
        userId: userInfo.userId
      }
    })
    this.setData({
      campId: res.msg
    })
  },

  // 营地信息表单校验
  showToast(title) {
    wx.showToast({
      title: title,
      icon: "error",
      mask: true,
      duration: 1500
    })
  },
  // 返回营地类型id
  campType(value) {
    return this.data.campTypes.indexOf(value) + 1
  },
  // 上传服务设施
  async subService() {
    let res = await http.addService({
      campId: this.data.campId,
      facilityIds: this.data.selectFacilitiesList
    })
    console.log(res)
    if (res.code == 200) {
      wx.redirectTo({
        url: `../detail/detail?campId=${this.data.campId}`,
      })
    }
  },
  // 获取营地详细信息方法并赋值
  async obtainDetail(id) {
    let {
      data
    } = await detailCamp(id)
    console.log(data)
    this.setData({
      address: data.address,
      campId: data.campId,
      name: data.campName,
      campImgs: data.imageUrl.split(","),
      list: data.imageUrl.split(","),
      type: this.data.campTypes[data.campType - 1],
      introduce: data.introduce,
      latitude: data.latitude,
      contacts: data.linkman,
      campLocation: data.location,
      longitude: data.longitude,
      phone: data.phone,
      time: data.specificTime,
      timeType: data.timeType,
      userType: data.userType,
    })
    if (this.data.userType == 1) {
      //获取服务设施
      await this.getFacilitiesList()
      // 获取运营者服务设施
      await this.obtainList(this.data.campId)
    }

  },
  // 获取运营者服务设施
  async obtainList(id) {
    let {
      data
    } = await seekList(id)
    let list = this.data.facilitiesList
    console.log(data);
    const arr = []
    for (let i = 0; i < data.length; i++) {
      for (let j = 0; j < data[i].facilities.length; j++) {
        arr.push(data[i].facilities[j].facilityId)
        let id = data[i].facilities[j].facilityId
        for (let k = 0; k < list.length; k++) {
          for (let m = 0; m < list[k].facilities.length; m++) {
            if (id == list[k].facilities[m].facilityId) {
              list[k].facilities[m].state = 2
            }
          }
        }
      }
    }
    this.setData({
      facilitiesList: list,
      selectFacilitiesList: arr
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    this.setData({
      campId: options.campId
    })
    console.log(options.campId);
    // 获取营地详细信息
    const id = options.campId
    await this.obtainDetail(id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

})